package com.newbingo.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Hashtable;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class GamePlayEngine {
	private ScriptEngine scriptEngine = null;
	private CompiledScript compiledScript = null;
	private String scriptType;
	private String scriptContent;	
	private static Map<String, GamePlayEngine> playEngines = new Hashtable<String, GamePlayEngine>();

	public static GamePlayEngine getGamePlayEngine(String scriptType, String scriptContent) throws ScriptException {
		GamePlayEngine gpe = playEngines.get(scriptContent);
		if (gpe == null) {
			gpe = new GamePlayEngine(scriptType, scriptContent);
			playEngines.put(scriptContent, gpe);
		}
		return gpe;
	}

	protected GamePlayEngine(String scriptType, String scriptContent) throws ScriptException {
		this.scriptType = scriptType;
		this.scriptContent = scriptContent;
		if (scriptType==null) scriptType="JavaScript";
		scriptEngine = new ScriptEngineManager().getEngineByName(scriptType);
		Compilable compEngine = (Compilable)scriptEngine;
		compiledScript = compEngine.compile(scriptContent);
	}

	public Object getWinningCell(List<Lottery> lotteries) throws ScriptException {
		scriptEngine.put("lotteries", lotteries);
		return compiledScript.eval();
	}
	public Object getWinningCell(List<Lottery> lotteries, List<Lottery> pickLotteries)
			throws ScriptException {
		scriptEngine.put("lotteries", lotteries);
		scriptEngine.put("pickLotteries", pickLotteries);
		return compiledScript.eval();
	}
	public int hashCode() {
		return scriptContent.hashCode();
	}
	public boolean equals(Object o) {
		if (o instanceof GamePlayEngine) {
			GamePlayEngine gpe = (GamePlayEngine) o;
			return (this.scriptContent.equals(gpe.scriptContent));
		}
		return false;
	}
}
